package com.xuanwoa.rabbit.amqp.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * Description
 *
 * @author: xuanwoa
 * @since: 2020/11/15
 */
@RestController
@RequestMapping("amqp")
@Slf4j
public class AMQPController {
    private final Queue queue = new ArrayDeque();


    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping("send")
    public String send(@RequestParam String msg) {
        //默认会发送到Exchange: (AMQP default)
        //The default exchange is implicitly bound to every queue, with a routing key equal to the queue name. It is not possible to explicitly bind to, or unbind from the default exchange. It also cannot be deleted.
        amqpTemplate.convertAndSend("myqueue", msg);
        return msg;
    }

    @GetMapping("receive")
    public String receive() {
        return String.valueOf(queue.poll());
    }

    @RabbitListener(id = "a", queues = "myqueue")
    public void processMsg(String msg) {
        log.info("received msg {}",msg);
        queue.offer(msg);
    }

}
